package com.canbot.u05.activity.attendance;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.MainApplication;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.AttendanceExcelAdapter;
import com.canbot.u05.bean.Attendance;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.ConstUtils;
import com.canbot.u05.utils.ExcelKqDownLoadLoader;
import com.canbot.u05.utils.FileUtil;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.CenterDialog;
import com.canbot.u05.view.IButtonClickListerner;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 考勤信息统计界面
 */
public class AttendanceStatisticsActivity extends BaseActivityNoTitle implements View.OnClickListener, AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {

        private static final String TAG = "AttendanceStatisticsActivity";

        private String[] fileName = new String[]{"u05_kqxx_001.wav", "u05_kqxx_002.wav", "u05_kqxx_003.wav"};

        private ImageView imageView_back;

        private RelativeLayout rlNoData;

        private GridView gvExcel;

        private AttendanceExcelAdapter adapter;

        private Dialog dialogLoading;

        private List<String> allMonth;

        private ExcelKqDownLoadLoader downLoadLoader;

        private String month;

        private CenterDialog deleteDialog;


        private Handler mHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                        LoadingDialogUtils.closeDialog(dialogLoading);//取消加载框
                        setAdapter(allMonth);

                        FileUtil.deleteDir(new File(ConstUtils.PATH_SD + "/kq/"));
                        //下载文件
                        downLoadLoader = new ExcelKqDownLoadLoader(AttendanceStatisticsActivity.this);
                        downLoadLoader.execute(JSON.toJSONString(allMonth));
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_attendance_statistics);

                setViews();
                int index = (int) (Math.random() * fileName.length);
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.AUDIO_ATTENDANCE_DIR + fileName[index]);
//                if (!isSuccess){
//                }
                MainApplication.getInstance().downLoadSuccess = false;
                initData();


        }

        /**
         * 获取月份
         *
         * @param data
         * @return
         */
        private List<String> getMonth(List<Attendance> data) {
                List<String> monthList = new ArrayList<>();
                if (data != null && data.size() != 0) {
                        for (int i = 0; i < data.size(); i++) {
                                //yyyy-MM
                                String month = data.get(i).getMonth();
                                if (!monthList.contains(month)) {
                                        monthList.add(month);
                                }
                        }
                        return monthList;
                }
                return null;
        }

        private void initData() {


                //获取考勤月份信息
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("all", "all");

                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "attendanceInfo", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {

                                Logger.e(TAG, "result=" + result);
                                final JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class);
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (jsonResponse.getRc() == 0) {
                                                        Logger.e(TAG, "结果=" + jsonResponse.getResult().toString());
                                                        String resultString = jsonResponse.getResult().toString();
                                                        allMonth = new ArrayList<String>();
                                                        if (resultString.contains(",")) {
                                                                String[] l = resultString.split(",");
                                                                for (int i = 0; i < l.length; i++) {
                                                                        if (l[i].contains("[")) {
                                                                                l[i] = l[i].replace("[", "");
                                                                        }
                                                                        if (l[i].contains("\"")) {
                                                                                l[i] = l[i].replace("\"", "");
                                                                        }
                                                                        if (l[i].contains("]")) {
                                                                                l[i] = l[i].replace("]", "");
                                                                        }
                                                                        allMonth.add(l[i]);
                                                                }
                                                        }
                                                        else {
                                                                if (resultString.contains("[")) {
                                                                        resultString = resultString.replace("[", "");
                                                                }
                                                                if (resultString.contains("\"")) {
                                                                        resultString = resultString.replace("\"", "");
                                                                }
                                                                if (resultString.contains("]")) {
                                                                        resultString = resultString.replace("]", "");
                                                                }
                                                                allMonth.add(resultString);
                                                        }

                                                        Logger.e(TAG, "allmonth结果=" + allMonth.toString());
                                                        mHandler.sendEmptyMessageDelayed(1,1500);
                                                }
                                                else {
                                                        allMonth = new ArrayList<String>();
                                                        //无打卡信息
                                                        gvExcel.setVisibility(View.INVISIBLE);
                                                        rlNoData.setVisibility(View.VISIBLE);
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                Logger.e("save", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(AttendanceStatisticsActivity.this).showText(AttendanceStatisticsActivity.this.getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        private void setAdapter(List<String> data) {
                Logger.e(TAG, "setAdapter=" + data.toString());
                adapter = new AttendanceExcelAdapter(this, data);
                gvExcel.setAdapter(adapter);
        }

        /**
         * 用户考勤信息显示界面
         */
        private void setViews() {
                rlNoData = (RelativeLayout) findViewById(R.id.rl_no_data);
                imageView_back = (ImageView) findViewById(R.id.imageView_back);
                gvExcel = (GridView) findViewById(R.id.attendance_excel_gv);
                imageView_back.setOnClickListener(this);
                gvExcel.setOnItemClickListener(this);
                gvExcel.setOnItemLongClickListener(this);

        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.imageView_back:
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;

                }

        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                //传入 月份
                month = allMonth.get(position);
                Logger.e(TAG, "点击 月：" + month);
                //跳转界面加载数据
                Intent intent = new Intent(this, AttendanceShowInfoActivity.class);
                intent.putExtra("month", month);
                startActivity(intent);
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);

        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                adapter.setShowDelete(true);
                adapter.setOnDelteListener(new AttendanceExcelAdapter.OnDeleteClickListener() {
                       @Override
                       public void onDelete(final int index) {
                               //弹出确认窗口
                               deleteDialog = new CenterDialog(AttendanceStatisticsActivity.this, R.style.centerdialog, "确定删除" + allMonth.get(index) + ".xls吗？", "", "", R.drawable.icon_delete_01, R.drawable.icon_dialogyes_00, new IButtonClickListerner() {
                                       @Override
                                       public void doBtnRight() {
                                               deleteMonthData(index);
                                       }

                                       @Override
                                       public void doBtnLeft() {
                                               deleteDialog.dismiss();
                                               adapter.setShowDelete(false);
                                               adapter.notifyDataSetChanged();
                                       }
                               });
                               deleteDialog.show();
                       }
               });


                return true;


//                return false;
        }

        private void deleteMonthData(final int index){
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload));
                Logger.e("deleteMonthData", "deleteMonthData:" + allMonth.get(index));
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("delete", allMonth.get(index));


                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "settingKqGroup", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(final String result) {

                                Logger.e("save", "onSuccess:" + result);
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                                JsonResponse jsonResponse = JSON.parseObject(result,JsonResponse.class);
                                                switch (jsonResponse.getRc()){
                                                        case -1:
                                                                ToastTools.newInstance(AttendanceStatisticsActivity.this).showText(AttendanceStatisticsActivity.this.getString(R.string.delete_failed));
                                                                break;
                                                        case 0:
                                                                ToastTools.newInstance(AttendanceStatisticsActivity.this).showText(AttendanceStatisticsActivity.this.getString(R.string.deleted_successfully));
                                                                File file = new File(ConstUtils.PATH_SD_ROOT + "/kq/"+allMonth.get(index) + ".xls");
                                                                if (file.exists()){
                                                                        file.delete();
                                                                }
                                                                allMonth.remove(index);
                                                                adapter.setShowDelete(false);
                                                                adapter.notifyDataSetChanged();

//                                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.AUDIO_ATTENDANCE_DIR + "u05_szcg_002.wav");
                                                                break;
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("save", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(AttendanceStatisticsActivity.this).showText(AttendanceStatisticsActivity.this.getString(R.string.network_error));
                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                        }
                                });
                        }
                });
        }


        @Override
        protected void onPause() {
                if (dialogLoading != null && dialogLoading.isShowing()){
                        LoadingDialogUtils.closeDialog(dialogLoading);
                }
                super.onPause();
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                mHandler.removeCallbacksAndMessages(null);
        }
}
